#include "Win32FileSystem.h"
#include "FileStream.h"
#include <fstream>
#include <functional>
#include <Shlwapi.h>

NS_B2D_BEGIN

Win32FileSystem::Win32FileSystem(void)
{
}

Win32FileSystem::~Win32FileSystem(void)
{
}

StreamPtr Win32FileSystem::getStream(const string& path) const
{
	auto ptr = new FileStream(path);
	return StreamPtr(ptr);
}

bool Win32FileSystem::fileExists(const string& path) const
{
	std::ifstream fs(path);
	return fs;
}

bool Win32FileSystem::getListOfFiles(std::vector<string>& _output, const string& _path, bool _recursive) const
{
	std::function<bool(std::vector<string>&, const string&, bool)> find_function =
		[&](std::vector<string>& output, const string& path, bool recursive)
	{
		HANDLE hFind = INVALID_HANDLE_VALUE;  
		WIN32_FIND_DATA ffd;

		string fPath = path+"/*";
		hFind = FindFirstFile(fPath.c_str(), &ffd);
		if(!hFind) return false;

		do  
		{ 
			bool isDirectory = ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;  
			if(isDirectory)  
			{  
				if(recursive)
				{
					find_function(output, path+"/"+ffd.cFileName, recursive);
				}
			}  
			else  
			{  
				output.push_back(path+"/"+ffd.cFileName);
			}  
		}
		while(FindNextFile(hFind, &ffd) != 0);  
		FindClose(hFind);
		return true;
	};

	return find_function(_output, _path, _recursive);
}

string Win32FileSystem::getFileExtension(const string& path) const
{
	return PathFindExtension(path.c_str());
}


NS_B2D_END